<template>
  <div class="student-info-container">
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>
      <el-form :model="infoForm" label-width="120px" ref="formRef" :rules="rules">
        <el-form-item label="学号">
          <el-input v-model="infoForm.student_number" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="infoForm.student_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-input :value="infoForm.student_sex === 1 ? '男' : '女'" disabled></el-input>
        </el-form-item>
        <el-form-item label="生日">
          <el-input v-model="infoForm.student_birthday" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="student_email">
          <el-input v-model="infoForm.student_email"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="infoForm.class_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="专业">
          <el-input v-model="infoForm.major_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="infoForm.password" type="password" placeholder="不修改请留空"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">更新信息</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getStudentInfoAPI, updateStudentInfoAPI } from '@/api/student/info.js'
import { ElMessage } from 'element-plus'

const formRef = ref(null)
const infoForm = reactive({
  student_number: '',
  student_name: '',
  student_sex: '',
  student_birthday: '',
  student_email: '',
  class_name: '',
  major_name: '',
  password: ''
})

const rules = {
  student_email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]
}

const fetchStudentInfo = async () => {
  const { data } = await getStudentInfoAPI()
  if (data.status === 200) {
    Object.assign(infoForm, data.data)
  }
}

onMounted(fetchStudentInfo)

const handleSubmit = async () => {
  await formRef.value.validate()
  const payload = {
    student_email: infoForm.student_email
  }
  if (infoForm.password) {
    payload.password = infoForm.password
  }
  const { data } = await updateStudentInfoAPI(payload)
  if (data.status === 200) {
    ElMessage.success('更新成功')
    infoForm.password = '' // 清空密码字段
  } else {
    ElMessage.error(data.msg || '更新失败')
  }
}
</script>

<style lang="scss" scoped>
.student-info-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}
.info-card {
  width: 600px;
}
</style>
